package cn.nit.blog.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * Created by wjx on 2023/3/27 16:58
 */

@Service
public class LikeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // blog:like:post:10 [101,102,103]
    private String likeKey = "blog:like:post:%s";

    public boolean isLike(Integer postId, Integer userId, Integer type) {
        // 2.准备点赞key(保存在redis的Set结构)
//        String key = String.format(likeKey, postId);
        String key = getLikeKey(type,postId);
        return stringRedisTemplate.opsForSet().isMember(key, userId.toString());
    }

//    同时获取对帖子和对评论的点赞
    private String getLikeKey(Integer type, Integer postId) {
        String typeName = null;
        if (type == 1) {
            typeName = "post";
        } else if (type == 2) {
            typeName = "comment";
        }
        return String.format(likeKey, typeName,postId);
    }

    public void removeLike(Integer postId,Integer type, Integer userId) {
        String key = getLikeKey(postId,type);
        stringRedisTemplate.opsForSet().remove(key, userId.toString());
    }

    public void addLike(Integer postId,Integer type, Integer userId) {
        String key = getLikeKey(postId,type);
        stringRedisTemplate.opsForSet().add(key, userId.toString());
    }

    public Long likeSize(Integer postId,Integer type) {
        String key = getLikeKey(postId,type);
        return stringRedisTemplate.opsForSet().size(key);
    }
}
